package com.catsic.practice.service;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.catsic.practice.entity.TaskDTO;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: zhangzf
 * @CreateTime: 2025-10-31  16:20
 * @Description: 12328热线工单申请流程服务
 */
@Service
@Slf4j
public class HotLineApproveService {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private HistoryService historyService;

    /**
     * 启动审批流程
     */
    public ProcessInstance startProcess(String policyRegulationsAssignee) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("policyRegulationsAssignee", policyRegulationsAssignee); //设置政策法规科审批人
        variables.put("responsibleDepartmentAssignee", "responsible_default_user");
        variables.put("agencyAssignee", "agency_default_user");
        variables.put("reviewAssignee", "review_default_user");
        variables.put("leaderAssignee", "leader_default_user");
        variables.put("hotlineLeaderAssignee", "hotline_leader_default_user");
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("policy_approval_process",variables);
        log.info("审批流程启动成功，流程实例ID: {}", processInstance.getId());
        List<Task> tasks = taskService.createTaskQuery()
                .processInstanceId(processInstance.getProcessInstanceId())
                .list();
        tasks.stream().forEach(t -> {
            log.info("任务ID: {}, 任务名称: {}, 办理人: {}, 候选人: {}",
                    t.getId(), t.getName(), t.getAssignee());
        });
        return processInstance;
    }

    /**
     * 查询用户待办任务
     */
    public List<TaskDTO> getUserTasks(String userId){
        List<Task> tasks = taskService.createTaskQuery()
                .taskCandidateOrAssigned(userId)
                .orderByTaskCreateTime()
                .desc()
                .list();
        return tasks.stream().map(TaskDTO::fromTask).collect(Collectors.toList());
    }

    /**
     * 完成任务
     */
    public void approveTask(String taskId, String userId, String nextApproveId, boolean isRollback){
        Task task = validateTask(taskId, userId);

        // 在任务完成前设置任务变量
        taskService.setVariable(taskId, "nextAssignee", nextApproveId);
        taskService.setVariable(taskId, "rejectReason", isRollback ? "rollback" : "normal");

        Map<String, Object> variables = new HashMap<>();
        // 完成任务
        taskService.complete(taskId, variables);

        log.info("用户 {} 审批通过了任务 {}, 指定下一审批人: {}", userId, task.getName(), nextApproveId);
    }

    /**
     * 回退任务
     */
    public void rollbackTask(String taskId, String userId, String nextApproveId){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        // 认领任务
        taskService.claim(taskId, userId);
        Map<String, Object> variables = new HashMap<>();
        variables.put("rejectReason", "rollback");
        variables.put("nextAssignee", nextApproveId);
        taskService.complete(taskId, variables);
    }

    /**
     * 查询流程历史
     */
    public List<HistoricActivityInstance> queryProcessHistory(String processInstanceId){
        return historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();
    }

    /**
     * 查询流程定义
     */
    public List<ProcessDefinition> getProcessDefinitions() {
        return repositoryService.createProcessDefinitionQuery()
                .orderByProcessDefinitionVersion()
                .desc()
                .list();
    }

    /**
     * 在任务完成前设置流程变量，确保监听器能获取到正确的值
     */
    private void setProcessVariablesBeforeCompletion(Task task, String nextAssignee,boolean isRollback) {
        String processInstanceId = task.getProcessInstanceId();

        // 直接设置到流程实例变量中
        runtimeService.setVariable(processInstanceId, "nextAssignee", nextAssignee);
        runtimeService.setVariable(processInstanceId, "rejectReason", isRollback ? "rollback" : "normal");

        log.info("在任务完成前设置流程变量 - nextAssignee: {}, rejectReason: {}",
                nextAssignee, isRollback ? "rollback" : "normal");
    }

    private Task validateTask(String taskId, String userId) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        if (task == null) {
            throw new RuntimeException("任务不存在");
        }
        taskService.claim(taskId, userId);
        return task;
    }
}
